package com.ks.api.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ks.api.entity.KsConfig;
import com.ks.api.entity.KsEventData;
import com.ks.api.entity.KsUser;
import com.ks.api.entity.KsUserCostSummary;
import com.ks.api.mapper.KsConfigMapper;
import com.ks.api.mapper.KsEventDataMapper;
import com.ks.api.mapper.KsUserCostSummaryMapper;
import com.ks.api.mapper.KsUserMapper;
import com.ks.api.service.KsUserCostSummaryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户成本汇总数据服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class KsUserCostSummaryServiceImpl extends ServiceImpl<KsUserCostSummaryMapper, KsUserCostSummary> implements KsUserCostSummaryService {

    private final KsUserCostSummaryMapper ksUserCostSummaryMapper;
    private final KsEventDataMapper ksEventDataMapper;
    private final KsConfigMapper ksConfigMapper;
    private final KsUserMapper ksUserMapper;
    
    @Override
    public boolean saveCostSummary(KsUserCostSummary costSummary) {
        if (costSummary == null || costSummary.getOpenId() == null) {
            log.warn("成本汇总数据缺失关键字段，无法保存");
            return false;
        }
        
        try {
            // 删除已存在的记录
            LambdaQueryWrapper<KsUserCostSummary> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(KsUserCostSummary::getOpenId, costSummary.getOpenId());
            remove(wrapper);
            
            // 保存新记录
            costSummary.setCreateTime(LocalDateTime.now());
            return save(costSummary);
        } catch (Exception e) {
            log.error("保存成本汇总数据异常", e);
            return false;
        }
    }
    
    @Override
    public Map<String, Object> findCostSummaries(Integer page, Integer size, String nickId, String nickName) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 构建分页对象
            Page<KsUserCostSummary> pageParam = new Page<>(page, size);
            
            // 调用Mapper执行查询
            IPage<KsUserCostSummary> summaryPage = ksUserCostSummaryMapper.findByUser(pageParam, nickId, nickName);
            
            // 封装返回结果
            result.put("total", summaryPage.getTotal());
            result.put("pages", summaryPage.getPages());
            result.put("current", summaryPage.getCurrent());
            result.put("size", summaryPage.getSize());
            result.put("records", summaryPage.getRecords());
            
        } catch (Exception e) {
            log.error("查询成本汇总数据失败", e);
            throw new RuntimeException("查询成本汇总数据失败: " + e.getMessage());
        }
        
        return result;
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int calculateAndSaveCostSummaries(List<KsEventData> eventDataList) {
        if (eventDataList == null || eventDataList.isEmpty()) {
            return 0;
        }
        // 获取显示百分比配置
        KsConfig ksConfig = ksConfigMapper.getConfigValue("display_percent");
        String percentStr = ksConfig.getConfigValue();
        String percentQjStr = ksConfig.getConfigValueQj();
        double displayQjPercent = percentQjStr != null ? Double.parseDouble(percentQjStr) : 50;
        double displayPercent = percentStr != null ? Double.parseDouble(percentStr) : 50;





        String topPriceStr = ksConfig.getTopPrice();
        String minPriceStr = ksConfig.getMinPrice();

        double topPrice = topPriceStr != null ? Double.parseDouble(topPriceStr) : 0.5;
        BigDecimal topPriceBigDecimal = BigDecimal.valueOf(topPrice);
        double minPrice = minPriceStr != null ? Double.parseDouble(minPriceStr) : 0.5;
        BigDecimal minPriceBigDecimal = BigDecimal.valueOf(minPrice);

        LocalDateTime target = LocalDateTime.of(2025, 4, 8, 15, 0);
        LocalDateTime target1 = LocalDateTime.of(2025, 4, 14, 0, 0);

        List<KsUserCostSummary> summaries = new ArrayList<>();
        // 对每条事件数据单独处理
        for (KsEventData eventData : eventDataList) {
            if (eventData.getOpenId() == null || eventData.getCost() == null) {
                log.warn("事件数据缺失关键字段，跳过处理: {}", eventData);
                continue;
            }
            // 将成本从厘转换为元
            BigDecimal totalCostInYuan = eventData.getCost()
                    .divide(new BigDecimal("1000"), 2, RoundingMode.HALF_UP);

            if (minPriceBigDecimal.compareTo(totalCostInYuan) > 0){
                //总金额小于0.05 不计算
                log.error("总金额小于{} 不计算 不保存", minPriceBigDecimal);
                continue;
            }

            String eventData1 = eventData.getEventData();
            JSONObject jsonObject = JSON.parseObject(eventData1);
            String string = jsonObject.getString("app_id");
            boolean after = LocalDateTime.now().isAfter(target1);
            if ((string == null || string.isEmpty() || string.equals("1")) && after) {
                log.error("出现灵珠修真纪的用户  不计算价值");
                continue;
            }

            // 检测用户是不是8号之后的用户
            LambdaQueryWrapper<KsUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(KsUser::getOpenId,eventData.getOpenId());
            KsUser ksUser = ksUserMapper.selectOne(wrapper);

            if (ksUser != null) {
                // 判断是否大于目标时间
                if (!ksUser.getCreateTime().isAfter(target)) {
                    // 4月8号之前的数据  不处理
                    log.error("该用户是4月8号 14点之前的数据 不处理{}", ksUser.getCreateTime());
                    log.error("该用户是4月8号 14点之前的数据 不处理{}", ksUser.getOpenId());
                    continue;
                }
            }
            //log.info("======================={}", ksUser.getCreateTime());
            //log.info("====================={}", ksUser.getOpenId());

            // 默认采用 基础配置
            double multiplier = displayPercent / 100.0;
            if (displayPercent == displayQjPercent) {
                log.info("区间值相等  跳过计算");
            }else{
                //开始判断数据 是否是经常一元的
                BigDecimal cost = eventData.getCost();
                // 生成随机数
                BigDecimal bigDecimal = RandomUtil.randomBigDecimal(BigDecimal.valueOf(displayQjPercent), BigDecimal.valueOf(displayPercent));
                if (cost.compareTo(BigDecimal.valueOf(1000)) >= 0){
                    // 当前数据的值是 大于或者等于一块钱  开始校验是否连续一元
                    int i = RandomUtil.randomInt(0, 10);
                    if (i > 4){
                        //log.info("数据大于一块钱  但是随机值大于4 选择计算比例不变 维持原装,{}",multiplier);
                        // 不变
                    }else{
                        multiplier = bigDecimal.doubleValue() / 100.0;
                        //log.info("数据大于一块钱  但是随机值小于4 选择计算比例随机取值,{}",multiplier);
                    }
                }else {
                    multiplier = bigDecimal.doubleValue() / 100.0;
                    //log.info("数据小于一块钱  但是随机值小于4 选择计算比例随机取值,{}",multiplier);
                }
            }
            multiplier = Double.parseDouble(String.format("%.2f", multiplier));



            // 计算用户成本（应用显示百分比和上限）
            BigDecimal userCost = totalCostInYuan.multiply(BigDecimal.valueOf(multiplier));
            if (userCost.compareTo(topPriceBigDecimal) > 0) {
                userCost = topPriceBigDecimal;
            }
            
            // 计算系统成本（总成本减去用户成本）
            BigDecimal sysCost = totalCostInYuan.subtract(userCost);
            
            // 创建成本汇总对象
            KsUserCostSummary summary = new KsUserCostSummary();
            summary.setOpenId(eventData.getOpenId());
            summary.setEventDataId(eventData.getId()); // 设置关联的事件数据ID
            summary.setTotalCost(totalCostInYuan);
            summary.setUserCost(userCost);
            summary.setSysCost(sysCost);
            summary.setCreateTime(LocalDateTime.now());
            
            summaries.add(summary);
            log.info("最终比例为{},openId:{},evId{},total:{},user{},sys{}",
                    multiplier, eventData.getOpenId(),eventData.getEventId(),totalCostInYuan,userCost,sysCost
            );
        }
        
        // 批量保存
        if (!summaries.isEmpty()) {
            this.saveBatch(summaries);
        }
        
        return summaries.size();
    }

    @Override
    public Map<String, Object> findCostSummariesWithUserInfo(Integer page, Integer size, String startTime, String endTime, String nickName, String nickId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 构建分页对象
            Page<KsUserCostSummary> pageParam = new Page<>(page, size);
            
            // 调用Mapper执行查询
            IPage<KsUserCostSummary> costPage = ksUserCostSummaryMapper.findCostSummariesWithUserInfo(
                pageParam, nickId, nickName, startTime, endTime);
            
            // 获取统计数据
            Map<String, Object> todayStats = calculateStats(
                ksUserCostSummaryMapper.getTodayCostSummaries(nickId, nickName));
            
            Map<String, Object> yesterdayStats = calculateStats(
                ksUserCostSummaryMapper.getYesterdayCostSummaries(nickId, nickName));
            
            Map<String, Object> weekStats = calculateStats(
                ksUserCostSummaryMapper.getWeekCostSummaries(nickId, nickName));
            
            Map<String, Object> monthStats = calculateStats(
                ksUserCostSummaryMapper.getMonthCostSummaries(nickId, nickName));
            
            // 封装返回结果
            result.put("total", costPage.getTotal());
            result.put("pages", costPage.getPages());
            result.put("current", costPage.getCurrent());
            result.put("size", costPage.getSize());
            result.put("records", costPage.getRecords());
            
            // 添加统计数据
            Map<String, Object> stats = new HashMap<>();
            stats.put("today", todayStats);
            stats.put("yesterday", yesterdayStats);
            stats.put("week", weekStats);
            stats.put("month", monthStats);
            result.put("stats", stats);
            
        } catch (Exception e) {
            log.error("查询用户成本汇总数据失败", e);
            throw new RuntimeException("查询用户成本汇总数据失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 计算统计数据
     */
    private Map<String, Object> calculateStats(Map<String, Object> costData) {
        Map<String, Object> stats = new HashMap<>();
        
        if (costData == null) {
            stats.put("count", 0);
            stats.put("total_cost", 0.00);
            return stats;
        }
        
        stats.put("count", costData.get("count"));
        stats.put("total_cost", costData.get("total_cost"));
        
        return stats;
    }

    @Override
    public Map<String, Object> searchEvents(Integer page, Integer size, String nickId, String nickname) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 构建分页对象
            Page<KsUserCostSummary> pageParam = new Page<>(page, size);
            
            // 调用Mapper执行查询
            Page<KsUserCostSummary> summaryPage = ksUserCostSummaryMapper.findEventSearchSummaries(pageParam, nickId, nickname);
            for (KsUserCostSummary record : summaryPage.getRecords()) {
                record.setTotalCost(record.getUserCost().multiply(BigDecimal.valueOf(2)));
                record.setSysCost(record.getUserCost());
            }
            // 获取统计数据
            Map<String, Object> todayStats = ksUserCostSummaryMapper.getTodayCostSummaries(nickId, nickname);
            Map<String, Object> yesterdayStats = ksUserCostSummaryMapper.getYesterdayCostSummaries(nickId, nickname);
            Map<String, Object> weekStats = ksUserCostSummaryMapper.getWeekCostSummaries(nickId, nickname);
            Map<String, Object> monthStats = ksUserCostSummaryMapper.getMonthCostSummaries(nickId, nickname);
            
            // 封装返回结果
            result.put("total", summaryPage.getTotal());
            result.put("pages", summaryPage.getPages());
            result.put("current", summaryPage.getCurrent());
            result.put("size", summaryPage.getSize());
            result.put("records", summaryPage.getRecords());
            
            // 添加统计数据
            Map<String, Object> stats = new HashMap<>();
            stats.put("today", todayStats);
            stats.put("yesterday", yesterdayStats);
            stats.put("week", weekStats);
            stats.put("month", monthStats);
            result.put("stats", stats);
            
        } catch (Exception e) {
            log.error("查询事件数据失败", e);
            throw new RuntimeException("查询事件数据失败: " + e.getMessage());
        }
        
        return result;
    }

    @Override
    public Map<String, Object> getEventSearchStats(String nickId, String nickname) {
        return ksUserCostSummaryMapper.getEventSearchStats(nickId, nickname, null, null);
    }
}